﻿using System;
using System.Windows.Forms;

namespace Latin_Vocabulary_Indicator
{
    public partial class wordlist : Form
    {
        private byte _editFrom;
        private Latin_indicator _caller;
        private string _editPath;
        public bool modified = false;
        public wordlist(Latin_indicator caller, string editPath)
        {
            InitializeComponent();
            _caller = caller;
            _editPath = editPath;
            if (editPath != null) refresh_list();
        }

        private void refresh_list()
        {
            list.Items.Clear();
            if (_editPath != null)
            {
                short listcount = 0;
                name_.Text = _editPath;
                string[] input = fileOperator.textInput("Latin\\" + _caller.inFolder + "\\" + _editPath + ".lvi").Split('\n');
                foreach(string subput in input)
                {
                    ListViewItem newitem = new ListViewItem();
                    newitem.Text = (listcount++).ToString();
                    newitem.SubItems.Add(fileOperator.accentTransform( subput.Split('|')[0].Trim(),true));
                    for (byte x=1;x<=3;x++)newitem.SubItems.Add(subput.Split('|')[x].Trim());
                    list.Items.Add(newitem);
                }
            }
        }

        private void add_Click(object sender, System.EventArgs e)
        {
            Hide();
            new setword(this, -1).Show();
        }

        private void msg(string input)
        {
            Enabled = false; new message(input, () => { Enabled = true; Focus(); }).Show();
        }

        private void edit_Click(object sender, System.EventArgs e)
        {
            if (list.SelectedItems.Count != 1){msg("Only one word should be selected.");return;}
            new setword(this, (short)list.SelectedIndices[0]).Show();
            Hide();
        }

        private void delete_Click(object sender, System.EventArgs e)
        {
            if (list.SelectedItems.Count == 0)msg("No word is selected.");
            else
            {
                short[] deleteList = new short[list.SelectedIndices.Count];
                for (short x = 0; x <= list.SelectedIndices.Count - 1; x++) deleteList[x] = (short)list.SelectedIndices[x];
                short deleted = 0;
                for (short x = 0; x <= deleteList.Length - 1; x++) list.Items.RemoveAt(deleteList[x] - (deleted++));
                for (short x = 0; x <= list.Items.Count - 1; x++) list.Items[x].Text = x.ToString();
                modified = true;
            }
        }

        private void up_Click(object sender, System.EventArgs e)
        {
            if (list.SelectedItems.Count >= 0)
            {
                short[] moveList = new short[list.SelectedIndices.Count];
                for (short x = 0; x <= list.SelectedIndices.Count - 1; x++) moveList[x] = (short)list.SelectedIndices[x];
                for (short x = 0; x <= moveList.Length - 1; x++)
                {
                    if (moveList[x] != 0 && (x==0||moveList[x-1]+1!=moveList[x])){
                        list.Items.Insert(moveList[x]-1, (ListViewItem)list.Items[moveList[x]].Clone()).Text=(moveList[x]-1).ToString();
                        list.Items.RemoveAt(moveList[x] + 1);
                        list.Items[moveList[x]].Text = (Convert.ToInt16( list.Items[moveList[x]--].Text) + 1).ToString();
                    }
                }
                list.SelectedItems.Clear();
                foreach(short subshort in moveList)  list.Items[subshort].Selected = true;
                modified = true;
            }
        }

        private void down_Click(object sender, EventArgs e)
        {
            if (list.SelectedItems.Count >= 0)
            {
                short[] moveList = new short[list.SelectedIndices.Count];
                for (short x = 0; x <= list.SelectedIndices.Count - 1; x++) moveList[x] = (short)list.SelectedIndices[x];
                for (short x = (short)(moveList.Length - 1); x >= 0; x--)
                {
                    if (moveList[x] != list.Items.Count-1 && (x == moveList.Length - 1 || moveList[x + 1] - 1 != moveList[x]))
                    {
                        list.Items.Insert(moveList[x]+2, (ListViewItem)list.Items[moveList[x]].Clone()).Text = (moveList[x]+1).ToString();
                        list.Items.RemoveAt(moveList[x]);
                        list.Items[moveList[x]].Text = (Convert.ToInt32(list.Items[moveList[x]++].Text) - 1).ToString();
                    }
                }
                list.SelectedItems.Clear();
                foreach (short subshort in moveList) list.Items[subshort].Selected = true;
                modified = true;
            }
        }
        private void discard_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void confirm_Click(object sender, System.EventArgs e)
        {
            if (name_.Text.Trim() == "")
            {
                msg("File name shouldn't be empty.");
                return;
            }
            else if (list.Items.Count==0)
            {
                msg("At least it should contain one word..");
                return;
            }
            else if (_editPath==null || name_.Text != _editPath)
            {
                try
                {
                    fileOperator.textOutput("Latin\\" + _caller.inFolder + "\\" + name_.Text.Trim() + ".lvi","Latin Vocabulary Indicator");
                }
                catch (Exception exp)
                {
                    MessageBox.Show("Failed to create file (" + name_.Text.Trim() + "):\n"+exp.Message);
                    return;
                }
                finally
                {
                    System.IO.File.Delete("Latin\\" + _caller.inFolder + "\\" + name_.Text.Trim() + ".lvi");
                }
            }
            bool delOrg = true;
            foreach(ListViewItem subitem in _caller.filelist.Items)
                if (subitem.Text == name_.Text.Trim())
                {
                    delOrg = false;
                    break;
                }
            string toOutput = "";
            for (short x = 0; x <= list.Items.Count - 1; x++)
                toOutput += fileOperator.accentTransform( list.Items[x].SubItems[1].Text,false) + "|" + list.Items[x].SubItems[2].Text + "|" + list.Items[x].SubItems[3].Text + "|" + list.Items[x].SubItems[4].Text + (x!= list.Items.Count - 1?"\n":"");
            if (delOrg) System.IO.File.Delete("Latin\\" + _caller.inFolder + "\\" + _editPath + ".lvi");
            fileOperator.textOutput("Latin\\" + _caller.inFolder + "\\" + name_.Text.Trim() + ".lvi", toOutput);
            _caller.refresh_file();

            _caller.Show();
            _caller.Focus();

            _caller.filelist.SelectedItems.Clear();
            foreach (ListViewItem subitem in _caller.filelist.Items)
            {
                if (subitem.Text == name_.Text)
                {
                    subitem.Selected = true;
                    break;
                }
            }
            modified = false;
            Close();
        }

        private void list_DoubleClick(object sender, EventArgs e)
        {
            if (list.SelectedItems.Count == 1)edit_Click(null, null);
        }

        private void wordlist_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!modified) {
                _caller.Show();
                _caller.Focus();
            }else
            if(MessageBox.Show("Discard and return?", "Discard",MessageBoxButtons.YesNo) == DialogResult.No)           
                e.Cancel = true;            
            else
            {
                _caller.Show();
                _caller.Focus();
            }
        }
    }
}
